Create meshes dynamically¶
Most other mesh demos load geometry from local files or remote URLs.
In contrast, this example demonstrates how to load meshes directly from
in-memory data. Three different ASCII text–based mesh formats (OBJ, PLY,
and legacy VTK) are constructed as strings and loaded without reading
from disk.
In [1]:
import ipywidgets as widgets
from ipyniivue import NiiVue
nv = NiiVue()
obj_str = """# cube.obj
v 2.0 2.0 2.0
v 2.0 2.0 50.0
v 2.0 50.0 2.0
v 2.0 50.0 50.0
v 50.0 0.0 2.0
v 50.0 0.0 50.0
v 50.0 50.0 2.0
v 50.0 50.0 50.0
f 1 7 5
f 1 3 7
f 1 4 3
f 1 2 4
f 3 8 7
f 3 4 8
f 5 7 8
f 5 8 6
f 1 5 6
f 1 6 2
f 2 6 8
f 2 8 4
"""
ply_str = """ply
format ascii 1.0
element vertex 8
property float x
property float y
property float z
element face 6
property list uchar int vertex_index
end_header
0 0 0
0 0 10
0 100 10
0 100 0
100 0 0
100 0 10
100 100 10
100 100 0
4 0 1 2 3
4 7 6 5 4
4 0 4 5 1
4 1 5 6 2
4 2 6 7 3
4 3 7 4 0
"""
vtk_str = """# vtk DataFile Version 3.0
5-sided cylinder (triangulated)
ASCII
DATASET POLYDATA
POINTS 12 float
25 0 1
7 23 1
-20 14 1
-20 -14 1
7 -23 1
25 0 40
7 23 40
-20 14 40
-20 -14 40
7 -23 40
0 0 1
0 0 40
POLYGONS 20 80
3 0 1 5
3 1 6 5
3 1 2 6
3 2 7 6
3 2 3 7
3 3 8 7
3 3 4 8
3 4 9 8
3 4 0 9
3 0 5 9
3 10 1 0
3 10 2 1
3 10 3 2
3 10 4 3
3 10 0 4
3 11 5 6
3 11 6 7
3 11 7 8
3 11 8 9
3 11 9 5
"""
mesh_drop = widgets.Dropdown(
options=[("Select format…", None), ("PLY", "PLY"), ("OBJ", "OBJ"), ("VTK", "VTK")],
value=None,
description="Format",
)
def on_mesh_change(change):
"""Handle mesh change."""
f = change["new"]
if f == "PLY":
raw = ply_str.strip().encode("utf-8") # raw OBJ bytes
nv.load_from_array_buffer(raw, "rect.ply")
elif f == "OBJ":
raw = obj_str.strip().encode("utf-8") # raw OBJ bytes
nv.load_from_array_buffer(raw, "cube.obj")
else:
raw = vtk_str.strip().encode("utf-8") # raw OBJ bytes
nv.load_from_array_buffer(raw, "cylinder.vtk")
mesh_drop.observe(on_mesh_change, names="value")
# --- Layout ---
ui = widgets.VBox(
[
widgets.HBox([mesh_drop]),
nv,
]
)
# Display All
ui
Out[1]: